/***
 * 此js文件中的构造函数、方法用于修复异常api:::
 *
 * SetInterval Function构造函数 修复setInterval每次定时执行的偏差，适用于倒计时场景
 *
 */
// 参考地址：https://gitee.com/dmui/set-interval/blob/master/interval.js
// 本项目中使用，原因是刷新token的refreshToken存在定时器延时导致的token失效。即在某个时间点，interval定时器会因为某个原因在某一次不执行
// 导致本次的token失效，从而无法刷新

//修复setInterval每次定时执行的偏差，适用于倒计时场景
function SetInterval(callback, time) {
  this.start = performance.now();
  this.end;
  this.offset;
  this.loopNum = 0;
  this.timeoutTag = null;
  this.time = time;
  this.callback = callback;
  this.$set(time);
}

SetInterval.prototype.$set = function (_time) {
  let that = this;
  if (this.timeoutTag === undefined) return;
  clearTimeout(this.timeoutTag);
  this.timeoutTag = null;
  that.timeoutTag = setTimeout(function () {
    that.loopNum++;
    that.end = performance.now();
    that.callback();
    that.offset = that.end - that.start - that.time * that.loopNum;
    console.log("普通任务", that.loopNum + ' --- 延时：' + that.offset + ' 毫秒');
    if (that.offset > 0) {
      that.$set(that.time - that.offset);
    } else if (that.offset < 0) {
      that.$set(that.time + that.offset);
    } else {
      that.$set(that.time);
    }
  }, _time);
};
SetInterval.prototype.$clear = function () {
  clearTimeout(this.timeoutTag);
  //便于拦截区分，此处必须设置为undefined
  this.timeoutTag = undefined;
};

export {
  SetInterval
}
